#include "app_input.h"
#include "drv_pi.h"
io_t g_io;
io_t * gp_io = &g_io;


void app_input_init(void) 
{
  uint32_t index = 0;
  uint32_t mode = 0;
  for (index = 0; index< HEM_IN_PORT_NUM; index++) 
  {
    gp_io->inmode[index] = g_config.in_mode[index];
    mode = gp_io->inmode[index];
    if(index < 16)
      {
        if(mode == 2)//4~20mA,输入端口必须选择0~5V采样
        {
          g_I0_to_I15_ai_config[index] = 1;
        }
        else
        {
          g_I0_to_I15_ai_config[index] = 0;
        }
      }
      if((index >= 16) && (index < 18))
      {
        if(mode == 3)
        {
          g_pca9555_port_func[index-15] = 1;
        }
        else
        {
          g_pca9555_port_func[index-15] = 0;
        }
      }

      if((index >= 18) && (index < 26))
      {
        if(mode == 5)
        {
          g_DI0_to_DI15_config[index-18] = 1;
        }
        else
        {
          g_DI0_to_DI15_config[index-18] = 0;
        }
      }
      if((index >= 26) && (index < HEM_IN_PORT_NUM))//DPI配置
      {

      }
  }

}

int8_t g_pwmi_feedback_offset = 0;
/**
 * @brief 自动更新结构体gp_io参数中的输入信号
 * 如果使用结构体中的输入功能，该函数必须保留；
 * 建议将该函数放到1ms定时器中；
 */
void input_update(void) 
{
  uint32_t i = 0;
  float coefficient = 0;
  float offset = 0;

#if HEM_AI_NUM > 0
  for (i = 0; i < HEM_AI_NUM; i++) 
  {
    gp_io->ai[i] = drv_adc_get_ai(i);
  }
#endif
#if HEM_PWMI_NUM > 0
  for(i = 0; i < HEM_PWMI_NUM;i++)
  {
    gp_io->ai_pwmi[i] = drv_adc_get_pwmi_ad(i);

    if(gp_io->pwmi[i] > 0)
    {
			coefficient = (g_800_ma[i] - g_200_ma[i]);
      coefficient = 600/coefficient;
      offset = 200 - g_200_ma[i]*coefficient;
      gp_io->ai_pwmi[i] = gp_io->ai_pwmi[i]*coefficient + offset;
    }
  }
#endif
#if HEM_DI_NUM > 0
  for (i = 0; i < HEM_DI_NUM; i++) 
  {
     gp_io->di[i] = di_get_value(i);
  }
#endif

#if HEM_DPI_NUM > 0
  for (i = 0; i< HEM_DPI_NUM; i++) 
  {
    gp_io->pi[i] = get_pi_frequency(i);
    gp_io->pic[i] = get_pi_count(i);
  }
#endif

}
